const JWT = require("./jwt");
const { createResponse } = require("./responseHelper");
const sqlconfig = require("../mysql/config"); // 确保路径正确

const verifyToken = async (req, res, next) => {
  // 从请求头获取token
  const token = req.headers["authorization"];
  if (!token) {
    return createResponse(
      res,
      "AUTH_ERROR",
      null,
      "获取登录信息失败,请重新登录"
    );
  }

  try {
    // 验证token
    const decoded = await JWT.verifyToken(req, token);
    if (decoded.success) {
      // 从数据库中获取用户名
      const getUserNameSql = "SELECT user_name FROM users WHERE user_id = ?";
      sqlconfig.query(getUserNameSql, [decoded.user.userId], (err, result) => {
        if (err) {
          console.error("Database error:", err);
          return createResponse(res, "SERVER_ERROR", null, "服务器错误");
        }

        if (result.length === 0) {
          return createResponse(res, "AUTH_ERROR", null, "用户不存在");
        }

        // 将解码后的用户信息和从数据库获取的用户名添加到请求对象中
        req.user = {
          userId: decoded.user.userId,
          userName: result[0].user_name
        };
        next(); // 继续下一个中间件或路由处理器
      });
    } else {
      createResponse(res, "AUTH_ERROR", null, "获取登录信息失败,请重新登录");
    }
  } catch (error) {
    console.error("Token verification error:", error);
    createResponse(res, "AUTH_ERROR", null, "获取登录信息失败,请重新登录");
  }
};

module.exports = verifyToken;